package com.damacheng009.future.alarm.crawler;

import java.util.List;

import org.nutz.http.Http;
import org.nutz.http.Response;

import com.damacheng009.future.alarm.toolkit.GlobalConfig;
import com.damacheng009.future.alarm.vo.KLineVo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

public class SinaRealtimeCrawler {
	
	private static final String URL_PATTERN = "https://hq.sinajs.cn/?_=%s/&list=%s";

	public KLineVo getKLine(String code) {
		String content = wget(code);
		List<String> items = StrUtil.split(content, ',');

		KLineVo vo = new KLineVo();
		
		if (code.startsWith("sh") || code.startsWith("sz")) {
			vo.setO(items.get(1));
			vo.setL(items.get(5));
			vo.setC(items.get(3));
			vo.setH(items.get(4));
			vo.setV(items.get(9));
			
			vo.setD(items.get(30) + " " + items.get(31));
		} else if (code.startsWith("hf")) {
			vo.setC(items.get(0));
			vo.setH(items.get(4));
			vo.setL(items.get(5));
			vo.setO(items.get(8));
			vo.setP(items.get(9));
			
			vo.setD(items.get(6) + " " + items.get(6));
		} else {
			vo.setC(items.get(8));
			vo.setH(items.get(3));
			vo.setL(items.get(4));
			vo.setO(items.get(2));
			vo.setP(items.get(13));
			vo.setV(items.get(14));
			
			String time = items.get(1);
			String hour = time.substring(0, 2);
			String min = time.substring(2, 4);
			String sec = time.substring(4, 6);
			
			String today = DateUtil.today();
			today += " " + hour + ":" + min + ":" + sec;
			
			vo.setD(today);
		}

		return vo;
	}
	
	private String wget(String code) {
		if (!code.startsWith("hf") && !code.startsWith("sh") && !code.startsWith("sz")) {
			// 内盘
			code = "nf_" + code;
		}
		
		if (code.startsWith("JO")) {
			code = GlobalConfig.cngold2Sina.get(code);
		}
		
		String url = String.format(URL_PATTERN, String.valueOf(System.currentTimeMillis()), code);
		Response resp = Http.get(url, 3000);
		
		if (resp != null) {
			if (resp.getStatus() == 200) {
				System.out.println("请求成功:" + url);
				return clean(resp.getContent(), code);
			} else {
				System.err.println("URL NOT 200");
			}
		}
		
		return null;
	}
	
	private String clean(String originString, String code) {
		String tmp = null;
		if (code.startsWith("hf") || code.startsWith("sh") || code.startsWith("sz")) {
			tmp = originString.replace("var hq_str_" + code + "=\"", "");
		} else {
			tmp = originString.replace("var hq_str_hf_" + code + "=\"", "");
		}
				
		return tmp = tmp.substring(0, tmp.length() - 2).trim();
	}
}
